import traceback
import pymysql
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from config.config import Config


class Base:
    def connect_db(self):
        """
        连接数据库
        :return:
        """
        config = Config()
        self.db = pymysql.connect(host=config.get_db_host(), port=config.get_db_port(), user=config.get_db_user(),
                                  password=config.get_db_password(), database=config.get_db_help(), charset='utf8')
        return self.db

    def close_db(self):
        """
        关闭数据库
        :return:
        """
        self.db.close()

    def list_of_dict(self, sql):
        """
        查询数据库
        :param sql:
        :return:
        """
        db = self.connect_db()
        cursor = db.cursor(pymysql.cursors.DictCursor)
        cursor.execute(sql)
        result = cursor.fetchall()
        self.close_db()
        return result

    def insert_region(self,name):
        """插入地区数据"""
        conn = self.connect_db()
        cursor = conn.cursor()
        cursor.execute(f"INSERT INTO area (name) VALUES ('{name}')")
        conn.commit()
        cursor.close()
        conn.close()


    # 加载驱动
    def __init__(self, driver):
        self.driver = driver

    # 打开网址
    def open_url(self, url):
        self.driver.get(url)

    # 元素定位
    def find_element(self, loc, time_out=20, poll_frequency=0.5):
        try:
            WebDriverWait(self.driver, time_out, poll_frequency).until(EC.presence_of_element_located(loc))
            return self.driver.find_element(*loc)
        except Exception:
            traceback.format_exc()

    # 点击事件
    def click(self, loc):
        self.find_element(loc).click()

    # 输入事件
    def send_keys(self, loc, text):
        self.find_element(loc).send_keys(text)
